package cn.cheniy.swiftmark.common.handler;

import cn.cheniy.swiftmark.common.exception.SwiftMarkException;
import cn.cheniy.swiftmark.common.response.ServerResponseEntity;
import cn.hutool.core.util.CharsetUtil;
import com.fasterxml.jackson.databind.ObjectMapper;
import jakarta.servlet.http.HttpServletResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import java.io.IOException;
import java.io.PrintWriter;

/**
 * @author cheniy
 * @description 全局异常输出向客户端输出自定义响应内容-【发生异常时传入ServerResponseEntity，给前端输出对应的JSON信息】
 *  
 */
@Component
public class HttpHandler {

    private static final Logger logger = LoggerFactory.getLogger(HttpHandler.class);

    @Autowired
    private ObjectMapper objectMapper;

    public <T> void printServerResponseToWeb(ServerResponseEntity<T> serverResponseEntity) {
        // 步骤1：校验响应实体是否为空
        if (serverResponseEntity == null) {
            logger.info("print obj is null");
            return;
        }

        // 步骤2：获取当前请求的上下文
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        if (requestAttributes == null) {
            logger.error("requestAttributes is null, can not print to web");
            return;
        }

        // 步骤3：获取 HttpServletResponse 对象
        HttpServletResponse response = requestAttributes.getResponse();
        if (response == null) {
            logger.error("httpServletResponse is null, can not print to web");
            return;
        }

        // 步骤4：记录错误日志（假设响应包含错误信息）
        logger.error("response error: " + serverResponseEntity.getMsg());

        // 步骤5：设置响应头（编码、内容类型）
        response.setCharacterEncoding(CharsetUtil.UTF_8);
        response.setContentType(MediaType.APPLICATION_JSON_VALUE);

        // 步骤6：将响应实体序列化为JSON并写入响应流
        PrintWriter printWriter = null;
        try {
            printWriter = response.getWriter();
            printWriter.write(objectMapper.writeValueAsString(serverResponseEntity));
        } catch (IOException e) {
            throw new SwiftMarkException("io 异常", e);
        }
    }

}
